package com.bankcomm.ui.views;

import java.io.File;
import java.util.ArrayList;
import com.bankcomm.R;
import com.bankcomm.bean.ItemObject;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BOCMainHome;
import com.bankcomm.util.PinyinUtils;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.ui.WaitProgressDialog;
import com.rytong.tools.utils.Utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * LPCityView.java
 * @author cheng.l 2013-5-15 下午02:44:25
 */
public class LPCitySelectView extends LinearLayout{
	private BOCMainHome bv;
	private ArrayList<GroupItem> mGroups = new ArrayList<GroupItem>();
	
	private LinearLayout layout;
	private TextView tvCity;
	public PopupWindow mWindow;
	public BCMHomeView bcmHome;
	
	boolean isUniversity = false;
	
	private WaitProgressDialog wpd = null;
	public LPCitySelectView(Context context,TextView tv,BCMHomeView homeview) {
		super(context);
		// TODO Auto-generated constructor stub
		bv = (BOCMainHome) context;
		this.tvCity = tv;
		bcmHome = homeview;
		init();
	}
	
	public LPCitySelectView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		bv = (BOCMainHome) context;
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		if(null == wpd){
			wpd = new WaitProgressDialog(bv, "图片下载中...");		
			wpd.dialog_.setCancelable(false);
		}
		
		ScrollView scroll = new ScrollView(bv);
		scroll.setScrollbarFadingEnabled(false);
		scroll.setVerticalFadingEdgeEnabled(false);
		scroll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1));

		layout = new LinearLayout(bv);
		layout.setBackgroundColor(Color.WHITE);
		layout.setOrientation(LinearLayout.VERTICAL);
		layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1));

		scroll.addView(layout);
		LinearLayout bottom = new LinearLayout(bv);
		bottom.setBackgroundResource(R.drawable.select_city_bottom);
		bottom.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		bottom.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(null != mWindow && mWindow.isShowing()){
					mWindow.dismiss();
				}
			}
		});
		
		this.setPadding(0, 0, 0, 40);
		this.setOrientation(LinearLayout.VERTICAL);
		this.setBackgroundColor(Color.WHITE);
		this.addView(scroll);
		this.addView(bottom);
		this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
		createWindow();
	}
	
	/**
	 * 重置当前视图
	 */
	public void resetView(){
		if(null != layout){
			layout.removeAllViews();
		}
		if(null != mGroups){
			int size = mGroups.size();
			for(int i = 0;i < size;i++){
				layout.addView(this.getView(mGroups.get(i)));
			}
		}
	}
	
	/**
	 * 重置大学数据
	 * @param univers
	 */
	private void resetUniversity(ArrayList<ItemObject> univers){
		isUniversity = true;
		mGroups.clear();
		mGroups = null;
		mGroups = new ArrayList<GroupItem>();
		
		GroupItem pGroup = new GroupItem();
		pGroup.groupName = "普通本科院校";	
		pGroup.citys = new ArrayList<ItemObject>();
		
		GroupItem gGroup = new GroupItem();
		gGroup.groupName = "高职(专科)院校";	
		gGroup.citys = new ArrayList<ItemObject>();
		
		mGroups.add(pGroup);
		mGroups.add(gGroup);
		for(ItemObject item : univers){
			if(item.universityType == 0){
				pGroup.citys.add(item);
			}else{
				gGroup.citys.add(item);
			}
		}
		
		if(null != layout){
			layout.removeAllViews();
		}
		if(null != mGroups){
			int size = mGroups.size();
			for(int i = 0;i < size;i++){
				layout.addView(this.getUniversityView(mGroups.get(i)));
			}
		}
	}
	
	/**
	 * 重置当前的数据
	 */
	public void resetGroups(){
		mGroups.clear();
		mGroups = null;
		mGroups = new ArrayList<GroupItem>();
		String version = LPMid.getInstance().read("version");
		if(null != version && version.equalsIgnoreCase("university")){
			GroupItem provinceGroup = new GroupItem();
			provinceGroup.groupName = "学校所在省市";	
			provinceGroup.citys = LPMid.getInstance().um_.data.lists;
			mGroups.add(provinceGroup);
		}else{
			sortGroups();
		}
	}
	
	/**
	 * 创建PopupWindow
	 */
	private void createWindow() {
		// TODO Auto-generated method stub
		mWindow = new PopupWindow(this);
		mWindow.setBackgroundDrawable(new BitmapDrawable());
		mWindow.setWidth(WindowManager.LayoutParams.FILL_PARENT);
		mWindow.setHeight(WindowManager.LayoutParams.FILL_PARENT);
		mWindow.setTouchable(true);
		mWindow.setFocusable(true);
		mWindow.setOutsideTouchable(true);
		mWindow.setContentView(this);
		mWindow.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				if(isUniversity){
					resetGroups();
					resetView();
				}
				isUniversity = false;
				BCMHomeView.dismissWindow();
			}
		});
	}

	public void showWindow(){
		BCMHomeView.showWindow(mWindow);
	}

	/***
	 * 对城市进行排序，按字母排序
	 */
	private void sortGroups() {
		// TODO Auto-generated method stub
		if(null != bv.mData.lists){
			int size = bv.mData.lists.size();

			GroupItem group = null;
			for(int i = 0;i < size;i++){
				ItemObject item = bv.mData.lists.get(i);
				String fisrtChar = PinyinUtils.getFirtChar(item.name);
				if(i == 0){
					group = new GroupItem();
					createGroup(fisrtChar,item,group);
				}else{
					ItemObject preItem = bv.mData.lists.get(i-1);
					String preFirstChar = PinyinUtils.getFirtChar(preItem.name);
					if(!fisrtChar.equalsIgnoreCase(preFirstChar)){
						mGroups.add(group);
						group = new GroupItem();
						createGroup(fisrtChar,item,group);
					}else{
						createGroup(fisrtChar,item,group);
						if(i == size-1){
							mGroups.add(group);
						}
					}
				}
			}

			//热门城市,如果后台给的热门城市不存在，则不显示热门城市
			if(null != bv.mData.hotlists && bv.mData.hotlists.size() > 0){
				GroupItem hotGroup = new GroupItem();
				hotGroup.groupName = "热门城市";
				hotGroup.citys = bv.mData.hotlists ;
				mGroups.add(0,hotGroup);				
			}
		}
	}

	public void createGroup(String f,ItemObject item,GroupItem group){
		group.groupName = f;
		group.citys.add(item);
	}
	
	/**
	 * 得到view含有一个Title和GridView
	 * */
	public View getView(GroupItem group){
		View view = LayoutInflater.from(bv).inflate(R.layout.layout_city_group_item, null);
		((TextView) view.findViewById(R.id.goupTitle)).setText(group.groupName);
		
		GridView grid = (GridView)view.findViewById(R.id.groupGrid);
		grid.setSelector(new ColorDrawable(Color.TRANSPARENT));
		grid.setAdapter(new GridAdapter(group.citys));
		
		grid.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int p,
					long arg3) {
				// TODO Auto-generated method stub
				GridAdapter adapter = (GridAdapter) adapterView.getAdapter();
				ItemObject item = (ItemObject) adapter.getItem(p);
				
				String version = LPMid.getInstance().read("version");
				if(null != version && version.equalsIgnoreCase("university")){
					int provinceId = item.provinceID;
					ArrayList<ItemObject> universitys = LPMid.getInstance().um_.data.readUniversity(provinceId);
					resetUniversity(universitys);
				}else{
					if(null != mWindow && mWindow.isShowing()){
						mWindow.dismiss();
					}
					PackageManagerAndroid.ANDROIDDB.save("city_select",item.code+"|"+item.name+"|"+item.branch);
					tvCity.setText(item.name);
					//更新天气
					bcmHome.mTopView.gotoWeather(item.name);
				}
			}
		});
		return view;
	}
	
	/**
	 * 得到学校视图
	 * @return
	 */
	public View getUniversityView(GroupItem group){
		View view = LayoutInflater.from(bv).inflate(R.layout.layout_city_group_item, null);
		((TextView) view.findViewById(R.id.goupTitle)).setText(group.groupName);
		
		LPCityGridView grid = (LPCityGridView)view.findViewById(R.id.groupGrid);
		grid.setColumns(2);
		grid.setSelector(new ColorDrawable(Color.TRANSPARENT));
		grid.setAdapter(new GridAdapter(group.citys));
		
		grid.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int p,
					long arg3) {
				// TODO Auto-generated method stub
				GridAdapter adapter = (GridAdapter) adapterView.getAdapter();
				ItemObject item = (ItemObject) adapter.getItem(p);
				LPMid.getInstance().saveToSP("university_select", item.name+"|"+item.universityId+"|"+item.universityType);
				tvCity.setText(item.name);
				if(null != mWindow && mWindow.isShowing()){
					mWindow.dismiss();
				}
				
				//下载校徽
				String url = ConfigManager.SCHOOL_BADGE +"320_480/"+ item.universityId +".jpg";
				if(url != null && !"".equalsIgnoreCase(url)){
					loadUniversityImage(url);					
				}
			}
		});
		return view;
	}
	/**
	 * 自定义Adapter
	 * */
	public class GridAdapter extends BaseAdapter{

		private ArrayList<ItemObject> items;
		
		public GridAdapter(ArrayList<ItemObject> items){
			this.items = items;
			if(null == this.items){
				this.items = new ArrayList<ItemObject>();
			}
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(convertView == null){
				convertView = LayoutInflater.from(bv).inflate(R.layout.layout_city_item, null);
				holder = new ViewHolder();
				holder.tvName = (TextView)convertView.findViewById(R.id.cityName);
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder)convertView.getTag();
			}
			
			holder.tvName.setText(items.get(position).name);
			
			return convertView;
		}
	}
	
	/**
	 * 城市组item
	 * */
	public class GroupItem{
		public String groupName;
		public ArrayList<ItemObject> citys = new ArrayList<ItemObject>();
	}

	public class ViewHolder{
		private TextView tvName;
	}
	
	
	/**
	 * 下载校徽图片
	 * @param Url
	 */
	public void loadUniversityImage(final String url){
		File file = new File(Utils.SCHOOL_IMAGE_PATH+Utils.getUniversityID()+".png");
		if(file.exists()){
			return;
		}
		
		loadHandler.sendEmptyMessage(0);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = new Message();
				try {
					BitmapDrawable bitmap = Utils.getBitmapByDownload(url);
					if(null != bitmap){
						msg.what = 1;
						msg.obj = bitmap;
					}else{
						msg.what = 2;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					msg.what = 2;
					e.printStackTrace();
				}
				loadHandler.sendMessage(msg);
			}
		}).start();
	}
	
	
	/**
	 * 下载校徽图片 add by cheng.l
	 */
	private Handler loadHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what){
			case 0:
				wpd.show(null);
				break;
			case 1:
				if(null != msg.obj){
					Bitmap universityBitmap = ((BitmapDrawable)msg.obj).getBitmap();
					Utils.saveBitmap(Utils.SCHOOL_IMAGE_PATH, Utils.getUniversityID(), universityBitmap);
					if(null != universityBitmap && !universityBitmap.isRecycled()){
						universityBitmap.recycle();
						universityBitmap = null;
					}
					Utils.printOutToConsole("校徽图片下载成功！");
				}
				wpd.dismiss();
				break;
			case 2:
				Utils.printOutToConsole("校徽图片下载失败！");
				wpd.dismiss();
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	/**
	 * 释放资源
	 */
	public void releaseResources(){
		if(null != mGroups){
			for(GroupItem item : mGroups){
				if(null != item.citys){
					item.citys.clear();
					item.citys = null;
				}
			}
			
			mGroups.clear();
			mGroups = null;
		}
	}
}
